package okna;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPanel;

import komorki.Komorka;
import komorki.ManagerKomorek;

import stany.BinaryState;
import stany.State;




public class Plansza extends JPanel{

	private static final long serialVersionUID = 1L;
	private final int  x_poz = 20;
	private final int y_poz = 45;
	private final int width = 30;
	private final int height = 30;
	private  Color[] colors; 
	private String[] opisy;
	private int index = 0;
	
	private Okno parrent;
	
	private Komorka[][] komorki;
	
	public Plansza(Okno parrent,int row, int column){
		this.parrent = parrent;
		setBounds(x_poz, y_poz, width * row, height * column);
		Pendzel p = new Pendzel();
		this.addMouseListener(p);
		this.addMouseMotionListener(p);
		
		State s = new BinaryState();
		colors = s.getAvailableColors();
		opisy = s.getDescriptions();
		
	}
	
	public void changeSize(int row, int column){
		//cos nie halo bo heigh i width licza sobie po tyle samo
		setSize(column * height, row * width);
		//setBounds(x_poz, y_poz, row * width, column * height);
	}
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		for(int i = 0; i < ManagerKomorek.maxRow; i++){
			 for(int j = 0; j < ManagerKomorek.maxColumn; j++){
				 g.drawRect(komorki[i][j].getX(), komorki[i][j].getY(), width - 1, height - 1);
			 }
		 }
	}
	@Override
	public void paint(Graphics g) {
		super.paint(g);
		
		for(int i = 0; i < ManagerKomorek.maxRow; i++){
			 for(int j = 0; j < ManagerKomorek.maxColumn; j++){
				 g.setColor(komorki[i][j].getColor());
				 g.fillRect(komorki[i][j].getX(), komorki[i][j].getY(), width - 1, height - 1);
			 }
		 }
	}
	
	public  void changeColors(Color[] c, String[] o){
		colors = c;
		opisy = o;
		index = 0;
		parrent.changeColor(colors[0], opisy[0]);
	}
	
	public void setKomorki(Komorka[][] komorki) {
		this.komorki = komorki;
	}



	class Pendzel extends MouseAdapter{
		private int column,row;
		
		@Override
		public void mouseClicked(MouseEvent e) {
			//lewy przycisk myszy
			if(e.getButton() == MouseEvent.BUTTON1){
				if(validateCoords(e.getX(),e.getY())){
					komorki[row][column].setDefinitiveColor(colors[index]);
					Plansza.this.repaint();
				}
			}else{
				index ++;
				index %=colors.length; 
				parrent.changeColor(colors[index], opisy[index]);
			}
		}
		
		
		
		
		@Override
		public void mouseDragged(MouseEvent e) {
			if(validateCoords(e.getX(),e.getY())){
				komorki[row][column].setDefinitiveColor(colors[index]);
				Plansza.this.repaint();
			}
			
		}
		
		private boolean validateCoords(int x, int y){
			row = y/Plansza.this.height;
			column = x/Plansza.this.width;
			if(row < ManagerKomorek.maxRow && column < ManagerKomorek.maxColumn)
				return true;
			return false;
		}
	}
}


